<template>
    <div class="puzzle" id="puzzle"></div>
</template>
<script lang="ts" setup>
document.addEventListener('DOMContentLoaded',function(){
    const puzzle:HTMLElement | null = document.getElementById('puzzle')!
    const rows = 3
    const cols = 3
    const order =Array.from(Array(rows * cols).keys()).sort(()=>Math.random()-0.5)
    const width =puzzle.clientWidth / rows
    const height =puzzle.clientHeight / cols

    function createPuzzleBlocks(){
        order.forEach(function(index){
            const div = document.createElement('div')
            div.style.setProperty('--block-size',width + 'px')
            div.style.setProperty('--image-size','300px 300px')
            div.style.backgroundImage = `https://img2.baidu.com/it/u=996160632,2978157898&fm=253&fmt=auto&app=138&f=JPEG?w=567&h=441`;
            div.style.backgroundPositionX = -width * (index % cols) + 'px'
            div.style.backgroundPositionY = -height *Math.floor(index / cols) + 'px'
            // puzzle不为空 
           if(puzzle){
             puzzle.appendChild(div)
           }
        })
    }

    function swapBlocks(target:any,empty:any){
        const tempX = target.style.backgroundPositionX
        const tempY = target.style.backgroundPositionY
        target.style.backgroundPositionX = empty.style.backgroundPositionX
        target.style.backgroundPositionX = empty.style.backgroundPositionY
        empty.style.backgroundPositionX = tempX
        empty.style.backgroundPositionY = tempY
        target.classList.add('empty')
        empty.classList.removeItem('empty')
    }
    createPuzzleBlocks()
    puzzle.addEventListener('click',function(e){
       const target = e.target
       const empty= puzzle.querySelector('.empty')
       if(target !== puzzle && empty && target !== empty){
        swapBlocks(target,empty)
       }
    })
})

</script>
<style>
.puzzle {
  display: grid;
  grid-template-columns: repeat(3, var(--block-size));
  grid-template-rows: repeat(3, var(--block-size));
  gap: 5px;
  width: 300px;
  height: 300px;
}

.puzzle div {
  background-size: var(--image-size);
  cursor: pointer;
}
</style>